package com.example.shardingsphere.controller;

import com.example.shardingsphere.common.config.UserContextHolder;
import com.example.shardingsphere.common.errorcode.GlobalErrorCodeConstants;
import com.example.shardingsphere.common.result.CommonResult;
import com.example.shardingsphere.controller.param.PasswordRequestParam;
import com.example.shardingsphere.controller.param.UserParam;
import com.example.shardingsphere.controller.param.UserPasswordLoginParam;
import com.example.shardingsphere.controller.result.TableDataInfo;
import com.example.shardingsphere.controller.result.UserLoginResult;
import com.example.shardingsphere.entity.User;
import com.example.shardingsphere.fegin.ProductFeginClient;
import com.example.shardingsphere.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    @Resource
    private ProductFeginClient productFeginClient;

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @PostMapping("/users/register")
    public CommonResult<Boolean> register(@RequestBody User user) {
        Integer register = userService.register(user);
        return register > 0 ?
                CommonResult.success(true, "注册成功！") : CommonResult.error(GlobalErrorCodeConstants.UNKNOWN1);
    }

    @PostMapping("/users/login")
    public CommonResult<UserLoginResult> login(
            @Validated @RequestBody UserPasswordLoginParam param) throws Exception {
        UserLoginResult userLoginResult = userService.login(param);
        return CommonResult.success(userLoginResult, "登录成功！");
    }

    /**
     * 获取用户列表，使用分页
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     */
    @GetMapping("/users")
    public TableDataInfo<User> getUserList(@RequestParam(defaultValue = "0") int pageNum,
                                           @RequestParam(defaultValue = "10") int pageSize) {
        return userService.getUserList(pageNum, pageSize);
    }

    /**
     * 查询用户信息
     * 普通用户仅自己，管理员所有普通用户，超管全部
     */
    @GetMapping("/getUserInfo")
    public User getUserById(@RequestParam String userId) {
        try {
            // 使用BigDecimal处理大整数
            BigDecimal id = new BigDecimal(userId);
            return userService.getUserById(id.longValue());
        } catch (NumberFormatException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid user ID format");
        }
    }

    /**
     * 修改用户信息
     */
    @PutMapping("/updateUserById")
    public Boolean updateUserInfo(@RequestParam String userId,
                                  @RequestBody UserParam userParam) {
        try {
            // 使用BigDecimal处理大整数
            BigDecimal id = new BigDecimal(userId);
            return userService.canUpdateUser(id.longValue(),userParam);
        } catch (NumberFormatException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid user ID format");
        }
    }

    /**
     * 密码重置
     */
    @PostMapping("/users/resetPassword")
    public CommonResult<Boolean> resetPassword(
            @RequestBody PasswordRequestParam passwordRequestParam ){

        Long userId = passwordRequestParam.getUserId();
        String newPassword = passwordRequestParam.getNewPassword();
        String oldPassword = passwordRequestParam.getOldPassword();
        Boolean result = userService.resetPassword(userId,oldPassword,newPassword);
        return result ? CommonResult.success(result,"修改密码成功") : CommonResult.error(500,"修改密码失败");
    }

    /**
     * 测试
     *
     * @return
     */
    @RequestMapping("/str")
    public String ll() {

        //测试用户上下文
        System.out.println(UserContextHolder.getCurrentUserRole());
        System.out.println();
        System.out.println(UserContextHolder.getUser());
        System.out.println(UserContextHolder.getUser().getRole());
        System.out.println(UserContextHolder.getUser().getAttributes());
        String userRoleCode = productFeginClient.getUserRoleCode(UserContextHolder.getCurrentUserId());
        return userRoleCode;
    }
}